//
//  ViewController.swift
//  PDF-Demo
//
//  Created by lan on 2017/6/27.
//  Copyright © 2017年 com.tzshlyt.demo. All rights reserved.
//

import UIKit
import PDFKit
import JavaScriptCore
@objc(PDFViewer) class PDFViewer: CDVPlugin, showPDF {
    func returnMsg(success: Bool, pageNum: Int) {
        if success{
            pluginResult = CDVPluginResult(status: .ok,messageAs: ["pageNum":pageNum])
        }else{
            pluginResult = CDVPluginResult(status: .error, messageAs: ["pageNum":pageNum])
        }
        pluginResult.setKeepCallbackAs(true)
        self.commandDelegate.send(pluginResult, callbackId: command.callbackId)
    }
    
    func getUrl() -> String {
        return data?.value(forKey: "fileUrl") as? String ?? ""
    }
    
    func getDocument() -> PDFDocument {
        return self.document
    }
    func getData() -> NSDictionary {
        return self.data
    }
    var pluginResult:CDVPluginResult!
    var command:CDVInvokedUrlCommand!
    var pdfName:String!
    var data:NSDictionary!
    var document:PDFDocument!
    func cancel(pageNum:Int) {
        // 设置当前阅读页数
        returnMsg(success: true, pageNum:pageNum)
        self.viewController.dismiss(animated: false, completion: nil)
    }
    
    @objc func showPDF(_ command:CDVInvokedUrlCommand){
        self.command = command
        self.data = command.argument(at: 0) as? NSDictionary
        self.pdfName = data.value(forKey: "name") as? String ?? ""
        do{
            try testError()
        }catch{}
    }
    var wait:DispatchGroup!
    func testError() throws{
        let pdfUrl = data?.value(forKey: "fileUrl") as? String ?? ""
        self.document = PDFDocument(url: URL.init(string: pdfUrl)!)
        if self.document == nil{
            self.returnMsg(success: false, pageNum: data?.value(forKey: "pageNum") as? Int ?? 1)
        }else{
            let show = ShowPDFViewController()
            show.delegate = self
            show.modalPresentationStyle = .currentContext
            self.viewController.present(show,animated: true,completion: nil)
        }
    }
}
protocol showPDF:class{
    func cancel(pageNum:Int)
    func getData()->NSDictionary
    func returnMsg(success:Bool,pageNum:Int)
    func getDocument()->PDFDocument
    func getUrl()->String
}
protocol getFunc:class {
    func getData() -> String
}
enum OperationError : Error {
    case error
}
class ShowPDFViewController: UIViewController,UIWebViewDelegate,UITextFieldDelegate,PDFViewDelegate,BarDelegate{
    override var shouldAutorotate: Bool{
        get{
            return false
        }
        set{
            self.shouldAutorotate = false
        }
    }
    func cancel() {
        delegate?.cancel(pageNum: Int(pdfview.currentPage!.label!)!)
    }
    var delegate:showPDF?
    var delegate_getFunc:getFunc?
    var pdfdocument: PDFDocument!
    var pdfview: PDFView!
    var allCount:Int!
    var readPage:Int!
    var pdfUrl:String!
    var bar:NavigationBar!
    var showPage:ShowPage!
    open override var prefersStatusBarHidden: Bool{
        get{
            return isHiddenStatusBar
        }
        set{
            self.prefersStatusBarHidden = isHiddenStatusBar
        }
    }
    var wait:DispatchGroup!
    var isHiddenStatusBar:Bool = false
    override func viewDidLoad() {
        super.viewDidLoad()
        self.getStartData()
        self.showPage = ShowPage.init(pdfdocument: self.pdfdocument, pdfView: self.pdfview)
        self.view.addSubview(self.showPage)
        self.editPageNumber()
    }
    @objc func addNotes(){
    }
    func showPDF(){
        self.view.backgroundColor = UIColor.white
        pdfview = PDFView(frame: CGRect(x: 0, y: 64, width: view.frame.width, height: UIScreen.main.bounds.height-64))
        allCount = pdfdocument?.pageCount
        pdfview.document = pdfdocument
        pdfview.displayMode = .singlePageContinuous
        pdfview.autoScales = true
        pdfview.backgroundColor = UIColor.gray
        pdfview.interpolationQuality = .high
        pdfview.minScaleFactor = pdfview.scaleFactorForSizeToFit
        pdfview.go(to: (self.pdfdocument?.page(at: self.readPage - 1))!)
        view.addSubview(pdfview)
        pdfview.delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(editPageNumber), name: .PDFViewPageChanged, object: nil)
        let click = UITapGestureRecognizer(target: self, action: #selector(hidden))
        click.numberOfTapsRequired = 1
        for gestureRecognizer in pdfview.gestureRecognizers!{
            click.require(toFail: gestureRecognizer)
        }
        pdfview.addGestureRecognizer(click)
//        NotificationCenter.default.addObserver(self, selector: #selector(testHidden), name: .PDFViewPageChanged, object: nil)

    }
    func getStartData(){
        let data = delegate?.getData()
        self.pdfdocument = delegate?.getDocument()
        self.readPage = data?.value(forKey: "pageNum") as? Int ?? 1
        self.showPDF()
        self.bar = NavigationBar.init(pdfducument: self.pdfdocument, pdfView: self.pdfview, titleName:data?.value(forKey: "name") as? String ?? "PDF预览")
        self.bar.delegate = self
        self.view.addSubview(self.bar)
        // 获取pdf信息
    }
    @objc func testHidden(){
        pdfview.frame = CGRect(x: 0, y: 20, width: view.frame.width, height: view.frame.height-20)
        self.bar.isHidden = true
        setNeedsStatusBarAppearanceUpdate()
    }
    @objc func hidden(){
        self.bar.isHidden = !self.bar.isHidden
        var y = 20;
        if !self.bar.isHidden{
            y = 64;
        }
        pdfview.frame = CGRect(x: 0, y: CGFloat(y), width: view.frame.width, height: view.frame.height-CGFloat(y))
        setNeedsStatusBarAppearanceUpdate()
    }
    @objc func editPageNumber(){
        showPage.pageView.setTitle("\(pdfview.currentPage?.label ?? "1")/\(self.allCount ?? 1)", for: .normal)
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func goOtherApp(){
        DispatchQueue.main.async {
            let str = (self.delegate?.getUrl())!
            let activityController = UIActivityViewController(activityItems: [URL(string: str)!], applicationActivities: nil)
            activityController.modalPresentationStyle = .fullScreen
            activityController.completionWithItemsHandler = {
                (type, flag, array, error) -> Void in
                if flag == true {
//                    分享成功
                } else {
//                    分享失败
                }
            }
            self.present(activityController, animated: true, completion: nil)
        }
    }
}


